package com.example.qincetest.mvvm.first

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.qincetest.base.BaseViewModel
import com.example.qincetest.network.NetRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.Timer
import java.util.TimerTask

class FirstViewModel : BaseViewModel() {
    private val repository by lazy { NetRepository.instance }


    fun getArticleList(page: Int) {
        flowAsyncWorkOnViewModelScopeLaunch {
            repository.getArticleList(page)
//            repository.getArticleList(page).onEach {
//                errorMsgLiveData.postValue(it.data?.datas!![0].title)
//                android.util.Log.e("MainViewModel", "one 111 ${it.data?.datas!![0].title}")
//            }
        }
    }


    /*
    冷流
     */
    val timeFlow = flow {
        var time = 0
        while (true) {
            emit(time)
            delay(1000)
            time++
            Timber.d("flow-test $time");
        }
    }

    /**
     * 热流
     */
    val hotFlow = timeFlow.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0)

    fun startTimer() {
        val timer = Timer()
        timer.schedule(object :TimerTask() {
            override fun run() {
            }
        },0,1000)
    }
}